//
//  AddCaseController.m
//  quickDoctor
//
//  Created by zhaowei on 17/3/10.
//  Copyright © 2017年 SWS. All rights reserved.
//

#import "AddCaseController.h"
#import "DescCell.h"
#import "PhotoCell.h"
#import "FirstCell.h"
#import "DiseaseTypeController.h"
#import "DiseaseSubdivisionController.h"
#import <MBProgressHUD.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface AddCaseController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,MBProgressHUDDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong)UITableView *tableView;


@property (nonatomic,strong)UIButton *pushButton;
@end

static NSString *firstCell = @"firstCell";
static NSString *secondCell = @"secondCell";
static NSString *thirdCell = @"thirdCell";
@implementation AddCaseController {
    DescCell *_descCell;
    UITableViewCell *_typeCell;
    UITableViewCell *_divisionCell;
    PhotoCell *_photoCell;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI{
    
    self.title = @"添加病例";
    //添加右侧buttonItem
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(commitMessage)];
    self .navigationItem.rightBarButtonItem = buttonItem;
    
    //为右侧buttonItem添加点击事件
    
    //颜色
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    
    //添加全屏的tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    _tableView = tableView;
    //设置代理和数据源方法
    tableView.delegate = self;
    tableView.dataSource = self;
    
    //去掉上面的间隔
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0,0.1)];
    
    //预估行高
    tableView.estimatedRowHeight = 200;
    [tableView sizeToFit];
    
    //注册
    [tableView registerClass:[FirstCell class] forCellReuseIdentifier:firstCell];
    [tableView registerClass:[DescCell class] forCellReuseIdentifier:secondCell];
    [tableView registerClass:[PhotoCell class] forCellReuseIdentifier:thirdCell];
    
    
//    //添加手势
//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(hidesKeyBoard)];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self  action:@selector(hidesKeyBoard)];
//    [tableView addGestureRecognizer:tap];
     [tableView addGestureRecognizer:pan];
    
}

- (void)hidesKeyBoard {
    [self.tableView endEditing:YES];
}
#pragma mark
#pragma mark -代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 1) {
        return 200;
    }
    return 50;
}

#pragma mark
#pragma mark -数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID;
    //判断cell类型,来取决cellID
    if(indexPath.section == 0) {
        cellID = firstCell;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
        
        if(indexPath.row == 0) {
            cell.textLabel.text = @"疾病类型";
            cell.tag = 0;
            _typeCell =cell;
            
        }else {
            cell.textLabel.text = @"疾病细分";
            cell.tag = 1;
            _divisionCell = cell;
        }
        cell.detailTextLabel.text = @"请选择";
        cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
        
        return cell;
    }else {
        if(indexPath.row == 0) {
            cellID = secondCell;
            DescCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
            _descCell =cell;
            
        
            //隐藏选中效果
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }else {
            cellID = thirdCell;
            PhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
            _photoCell = cell;
            _pushButton = cell.photoButton;
            //隐藏选中效果
            //为button添加点击事件
            [_pushButton addTarget:self  action:@selector(pushToPhoto) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            return cell;
        }
    }
 
}
#pragma mark
#pragma mark -跳转到相册
- (void)pushToPhoto {
    //判断用户有没有开启访问权限
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    //应用没有被授权,或者用户否认应用程序访问相册
    if(author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
        //没有权限,去引导开启
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    pickerController.allowsEditing = YES;
    
    pickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:pickerController animated:YES completion:nil];
    
}


#pragma mark
#pragma mark -相片选择完成时调用的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        //获取图片
        UIImage *image = info[UIImagePickerControllerEditedImage];
        [_pushButton setBackgroundImage:image forState:UIControlStateNormal];
    }];
    
    
}

//取消选中和点击跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 0) {
        if(indexPath.row == 0) {
            
            //创建疾病类型控制器
            DiseaseTypeController *typeController = [[DiseaseTypeController alloc] init];
            [self.navigationController pushViewController:typeController animated:YES];
        }else {
            //判断疾病类型是否已经选择
            if([_typeCell.detailTextLabel.text isEqualToString:@"请选择"]) {
//                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
//                HUD.delegate = self;
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"❗️" message:@"请选择疾病类型" preferredStyle: UIAlertControllerStyleAlert];
                [self presentViewController:alert animated:YES completion:^{
                    
                    //完成时,创建定时器
                    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dismissAlert:) userInfo:alert repeats:NO];
                }];
    
            }else {
                //创建细分控制器
                DiseaseSubdivisionController *divisionController = [[DiseaseSubdivisionController alloc] init];
                [self.navigationController pushViewController:divisionController animated:YES];
            }
        }
    }
    
}

//取消alert
- (void)dismissAlert:(NSTimer *)timer {
//    self dismissViewControllerAnimated:<#(BOOL)#> completion:<#^(void)completion#>
    UIAlertController *alert = [timer userInfo];
    [alert dismissViewControllerAnimated:YES completion:nil];
    alert = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload:) name:@"pop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDivision:) name:@"divisionPop" object:nil];
    
    
}
- (void)reload:(NSNotification *)notification  {
    //取出字典中的字符串
    NSString *str = notification.userInfo[@"text"];
    //刷新
    _typeCell.detailTextLabel.text = str;
}
- (void)reloadDivision:(NSNotification *)notification {
    
    //取出字符串
    NSString *divisionStr = notification.userInfo[@"text"];
    //刷新
    _divisionCell.detailTextLabel.text = divisionStr;
}

#pragma mark
#pragma mark -pop提交信息
- (void)commitMessage {
    //获取当前时间
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    
    [dateFormatter setDateFormat:@"YYYY年-MM月-dd日 hh-mm-ss"];
    NSString *dateTime = [dateFormatter stringFromDate:date];
    
    
    //创建字典
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    [dictM setObject:_typeCell.detailTextLabel.text forKey:@"typeText"];
    [dictM setObject:_divisionCell.detailTextLabel.text forKey:@"divisionText"];
    [dictM setObject:_descCell.textView.text forKey:@"textViewText"];
    [dictM setObject:_photoCell.photoButton.currentBackgroundImage forKey:@"photoImage"];
    [dictM setObject:dateTime forKey:@"dateTime"];
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"caseCommit" object:nil userInfo:dictM];
    
    //pop
    [self.navigationController popViewControllerAnimated:YES];
}

@end
